import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';
import { createPaginationResponse, parsePaginationParams } from '@/lib/pagination';
import type { ChatLogPageParams, ChatLog } from '@/types/logs';
import { PaginationResponse } from '@/types/api-common';
import { Prisma } from '@prisma/client';

// POST /api/admin/chat/page - 获取聊天日志列表
async function handlePost(request: NextRequest): Promise<PaginationResponse<ChatLog>> {
  // 权限验证
  const authResult = await authenticateRequest(request);
  if (!authResult.success) {
    throw new Error(authResult.error || '认证失败');
  }

  const body: ChatLogPageParams = await request.json();
  const { page, pageSize, skip } = parsePaginationParams(body);
  
  const search = body.search || '';
  const role = body.role || '';
  const startDate = body.startDate;
  const endDate = body.endDate;

  // 构建查询条件
  const where: Prisma.ChatMessageWhereInput = {};


    // 角色筛选
    if (role) {
      where.role = role;
    }

    // 日期范围筛选
    if (startDate || endDate) {
      where.createdAt = {};
      if (startDate) {
        where.createdAt.gte = new Date(startDate);
      }
      if (endDate) {
        where.createdAt.lte = new Date(endDate + 'T23:59:59.999Z');
      }
    }

    // 计算分页
    const take = pageSize;

    // 查询数据
    const [items, total] = await Promise.all([
      prisma.chatMessage.findMany({     
        where,
        include: {
          session: {
            include: {
              user: {
                select: {
                  id: true,
                  username: true,
                }
              }
            }
          }
        },
        orderBy: {
          createdAt: 'desc'
        },
        skip,
        take
      }),
      prisma.chatMessage.count({ where })
    ]);

    // 格式化数据
    const formattedItems = items.map(item => ({
      id: item.id,
      chatItemId: item.id,
      chatId: item.sessionId,
      userId: item.session?.userId || '',
      username: item.session?.user?.username || '',
      role: item.role,
      content: item.content,
      createdAt: item.createdAt.toISOString()
    }));

  return createPaginationResponse(formattedItems as unknown as ChatLog[], total, page, pageSize);
}

export const POST = withMiddleware(handlePost);